﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

using GolfSigma.Inventory.Extension;

namespace GolfSigma.Inventory.Model
{
    [XmlRoot("Filter")]
    [Serializable]
    public class SearchFilter : IXmlSerializable
    {
        public Guid Id { get; set; }

        public string Key { get; set; }

        public string Value { get; set; }

        #region Constructors

        public SearchFilter() { }

        public SearchFilter(Guid id, string key, string value)
        {
            Id = id;
            Key = key;
            Value = value;
        }

        #endregion

        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            // Check to see if we were provided an id
            string filterId = reader.GetAttribute("id");
            if (!string.IsNullOrEmpty(filterId))
            {
                Guid? filterIdParsed = GuidExtension.ToGuid(filterId);
                if (filterIdParsed.HasValue)
                    Id = filterIdParsed.Value;
                else
                    throw new FormatException();
            }

            string key = reader.GetAttribute("key");
            string value = reader.GetAttribute("value");

            // Make sure we have a key
            if (string.IsNullOrEmpty(key))
                throw new FormatException();

            // Make sure we have a value
            if (string.IsNullOrEmpty(value))
                throw new FormatException();

            Key = key;
            Value = value;

            // Done reading
            reader.Read();
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteAttributeString("id", GuidExtension.ToStringNoHyphen(Id));
            writer.WriteAttributeString("key", Key);
            writer.WriteAttributeString("value", Value);
        }

        #endregion

        #region Post Parameters

        public Dictionary<string, string> GetPostParamters()
        {
            return GetPostParamters(default(int?));
        }

        public Dictionary<string, string> GetPostParamters(int? index)
        {
            string prefix = "filter.";

            // Create our result
            Dictionary<string, string> result = new Dictionary<string, string>();

            result.Add(StringExtension.Prefix("id", prefix, index), GuidExtension.ToStringNoHyphen(Id));
            result.Add(StringExtension.Prefix("key", prefix, index), Key);
            result.Add(StringExtension.Prefix("value", prefix, index), Value);

            // Return the params
            return result;
        }

        #endregion
    }
}
